package com.imoresoft.magic.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ambitor.grass.sql.dao.SuperDao;
import com.ambitor.grass.sql.data.Parameter;
import com.ambitor.grass.util.data.DataMap;
import com.ambitor.grass.util.data.IData;
import com.ambitor.grass.util.data.IDataset;
import com.imoresoft.agile.entity.Result;
import com.imoresoft.agile.property.TableName;
import com.taobao.api.domain.UserSubscribe;

public class Utils {

	protected static final Logger logger = LoggerFactory.getLogger(Utils.class);

	public static void main(String[] args) {
		System.out.println(getToday());
	}

	public static String getToday() {
		Date today = new Date();
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		return dateFormat.format(today);
	}

	@SuppressWarnings("unchecked")
	public static IData getSelection(SuperDao dao, String table,
			String keyColumn, String valueColumn) throws Exception {
		IData labels = new DataMap();
		String sql = "select " + keyColumn + "," + valueColumn + " from "
				+ table + " where valid_flag = '1' order by show_order";
		IDataset dataset = dao.queryListBySql(sql);
		if (dataset.count() == 0)
			return labels;
		for (int i = 0; i < dataset.count(); i++) {
			IData data = dataset.getData(i);
			labels.put(data.getString(keyColumn.toUpperCase()), data
					.get(valueColumn.toUpperCase()));
		}
		return labels;
	}

	public static String getLabelName(SuperDao dao, String itellLabel)
			throws Exception {
		IData labels = getSelection(dao, "td_p_intell", "intell_label",
				"label_name");
		return labels.getString(itellLabel, "未知");
	}

	public static String getStrategyClassOfSpeficLabel(SuperDao dao,
			String intellLabel) throws Exception {
		IData labels = getSelection(dao, "td_p_intell", "intell_label",
				"strategy_class");
		return labels.getString(intellLabel, Constants.DEFAULT_STRATEGY_CLASS);
	}

	public static String builderOrderStr(Result result) {
		int daysLeft = daysBetween(new Date(), (Date) result.getResult());
		String endDate = DateUtil.format2YMD((Date) result.getResult());
		String orderInfo = result.getMsg() + "授权到" + endDate + "，还有" + daysLeft
				+ "天过期。";
		return orderInfo;
	}

	public static int daysBetween(Date date1, Date date2) {
		if (date1 == null || date2 == null) {
			return 0;
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(date1);
		long time1 = cal.getTimeInMillis();
		cal.setTime(date2);
		long time2 = cal.getTimeInMillis();
		Long between_days = (time2 - time1) / (1000 * 3600 * 24);

		return between_days.intValue();
	}

	public static Result getUserClass(SuperDao dao, String userId,
			UserSubscribe userSubs) {
		Result taobaoVersion = getTaobaoVersion(userSubs);
		Result presentVersion = getPresentVersion(dao, userId);
		if (presentVersion.getCode() == -1 && taobaoVersion.getCode() == -1) {
			return taobaoVersion;
		}
		if (presentVersion.getCode() >= taobaoVersion.getCode()) {
			return presentVersion;
		} else {
			return taobaoVersion;
		}
	}

	private static Result getTaobaoVersion(UserSubscribe userSubs) {
		Result result = new Result(-1, "");
		if (userSubs == null || !"subscribeUser".equals(userSubs.getStatus())
				|| userSubs.getEndDate() == null
				|| userSubs.getEndDate().before(new Date())) {
			return result;
		}

		Long versionNo = userSubs.getVersionNo();
		if (versionNo == null || versionNo.intValue() <= 0) {
			return result;
		}
		int version = userSubs.getVersionNo().intValue();
		result.setCode(version);
		String versionName = null;
		switch (version) {
		case 1:
			versionName = "体验版";
			break;
		case 2:
			versionName = "标准版";
			break;
		case 3:
			versionName = "高级版";
			break;
		default:
			versionName = "未知版";
		}
		result.setMsg(versionName);
		result.setResult(userSubs.getEndDate());
		return result;
	}

	private static Result getPresentVersion(SuperDao dao, String userId) {
		Result result = new Result(-1, null);
		int presentVersion = -1;
		try {
			String sql = "select present_version,present_deadline from "
					+ TableName.TF_P_USER_SESSION
					+ " where present_deadline > now() and user_id = ? "
					+ " and present_version >0";
			Parameter p = new Parameter();
			p.add(userId);
			IDataset dataset = dao.queryListBySql(sql, p);
			if (dataset.size() > 0) {
				IData dataMap = dataset.getData(0);
				String version = dataMap.getString("PRESENT_VERSION");
				presentVersion = new Double(version).intValue();
				result.setCode(presentVersion);
				result.setMsg("[赠送VIP" + presentVersion + "版]");
				Date presentDeadline = (Date) dataMap.get("PRESENT_DEADLINE");
				result.setResult(presentDeadline);
			}
		} catch (Exception e) {
			logger.error("获取conn或查询数据库异常", e);
		}
		return result;
	}

	public static int getMaxInstallItems(int versionNo) {
		int maxInstallItems = 0;
		if (versionNo == 1) {
			maxInstallItems = Constants.MAX_TO_PROMOTE_NUM_LOW;
		} else if (versionNo == 2) {
			maxInstallItems = Constants.MAX_TO_PROMOTE_NUM_MIDDLE;
		} else if (versionNo == 3) {
			maxInstallItems = Constants.MAX_TO_PROMOTE_NUM_HIGH;
		} else {
			maxInstallItems = Constants.MAX_TO_PROMOTE_NUM_LOW;
		}
		return maxInstallItems;
	}

	/**
	 * 智能标签是否为简单标签，简单标签即一次安装过程中只需解析一次的标签
	 * 
	 * @param userProSetting
	 * @return
	 */
	public static boolean isIntellLabelSimple(String intellSetting) {
		String[] intellSettingArray = intellSetting.split(",");
		String[] labelStr = intellSettingArray[0].split(":");
		String intellLabel = labelStr[0];

		boolean isIntellLabelSimple = false;
		String simpleIntellLabels = PropertiesReader
				.getString("SIMPLE_INTELL_LABELS");
		if (StringUtils.isBlank(simpleIntellLabels)) {
			isIntellLabelSimple = true;
		} else {
			String[] simpleIntellLabelsArray = simpleIntellLabels.split(",");
			for (String str : simpleIntellLabelsArray) {
				if (str.equalsIgnoreCase(intellLabel)) {
					isIntellLabelSimple = true;
					break;
				}
			}
		}
		return isIntellLabelSimple;
	}

	public static String getProModuleNoticeText(String pro4Ipro) {
		if ("1".equals(pro4Ipro)) {// 加软件广告
			return "Powered By 淘助手";
		} else if ("2".equals(pro4Ipro)) {// 在推广模块上加软件过期通知
			return PropertiesReader.getString("IPRO_EXPIRED_NOTICE");
		} else {
			return StringUtils.EMPTY;
		}
	}

	@SuppressWarnings("unchecked")
	/**
	 * 解析INTELL_SETTING为字符串 举例：INTELL_SETTING = 1:3 解析成
	 * INTELL_SETTING_DESC=【本店最近上架的宝贝】3个
	 */
	public static IDataset getIntellSettings(SuperDao dao, IDataset result)
			throws Exception {
		IData labels = getSelection(dao, "td_p_intell", "intell_label",
				"label_name");
		for (int i = 0; i < result.size(); i++) {
			IData resultData = result.getData(i);
			String intellSetting = resultData.getString("INTELL_SETTING");
			if (StringUtils.isNotBlank(intellSetting)) {
				String[] intellSettings = intellSetting.split(",");
				String intellSettingDesc = "";
				for (int j = 0; j < intellSettings.length; j++) {
					if (StringUtils.isNotBlank(intellSettings[j])) {
						String[] intellSettingStrs = intellSettings[j]
								.split(":");
						String labelDesc = "";

						if (intellSettingStrs.length == 2) {
							String labelName = labels
									.getString(intellSettingStrs[0]);
							String intellNum = intellSettingStrs[1];
							labelDesc = "【" + labelName + "】" + intellNum + "个";
						}

						if (j == intellSettings.length - 1)
							intellSettingDesc += labelDesc;
						else
							intellSettingDesc += labelDesc + "，";
					}

				}

				resultData.put("INTELL_SETTING_DESC", intellSettingDesc);
			} else {
				resultData.put("INTELL_SETTING_DESC", "");
			}

		}
		return result;
	}
}
